package com.wwh.furns.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Albert
 * @date 2024/5/26-15:56
 * @describe
 */
public abstract class BasicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        //System.out.println("BasicServlet doPost()...");
        String action = req.getParameter("action");
        //System.out.println("action=" + action);

        //使用反射获取当前对象的方法
        //this就是请求的Servlet
        //declaredMethod方法 是请求的Servlet对应的action名字的方法，根据用户请求而变化
        //要满足action和servlet中的方法名保持一致
        //使用 模板模式+反射+动态绑定=》简化Servlet
        try {
            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //System.out.println("declaredMethod=" + declaredMethod);
            //使用方法对象，进行反射调用
            declaredMethod.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
